package controllers

import dao._
import implicits.Implicits._
import models.Tables._
import org.joda.time.DateTime
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, Codec, ControllerComponents}
import tool.FormTool
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import argonaut._
import Argonaut._
import ArgonautShapeless._
import org.joda.time.format.DateTimeFormat
import play.api.http.{ContentTypeOf, ContentTypes, Writeable}

/**
 * Created by Administrator on 2019/8/7
 */
class CompanyMemberController @Inject()(cc: ControllerComponents)(
  implicit val accountDao: AccountDao,
  implicit val companyMemberDao: CompanyMemberDao
) extends
  AbstractController(cc) {

  def add = Action.async { implicit request =>
    val data = FormTool.companyMemberForm.bindFromRequest().get
    val row = CompanyMemberRow(0, data.account, data.password, new DateTime(), data.companyName)
    companyMemberDao.insert(row).map { x =>
      Ok(Json.toJson("success!"))
    }
  }

  def all = Action.async { implicit request =>
    companyMemberDao.selectAll.map { x =>
      val array = x.map { y =>
        y.asJson
      }.toList
      Ok(array.asJson)
    }
  }

  def allCompany = Action.async { implicit request =>
    companyMemberDao.selectAll.map { x =>
      val array = x.map(_.companyName)
      Ok(Json.toJson(array))
    }
  }

  def delete = Action.async { implicit request =>
    val data = FormTool.idForm.bindFromRequest().get
    companyMemberDao.deleteById(data.id).map { x =>
      Ok(Json.obj("result" -> "success"))
    }
  }

  def getById = Action.async { implicit request =>
    val data = FormTool.idForm.bindFromRequest().get
    companyMemberDao.selectById(data.id).map { x =>
      Ok(x.asJson)
    }
  }

  def update = Action.async { implicit request =>
    val data = FormTool.companyMemberForm.bindFromRequest().get
    companyMemberDao.selectByAccountSome(data.account).flatMap { dbUser =>
      val row = dbUser.copy(password = data.password, companyName = data.companyName)
      companyMemberDao.update(row).map { x =>
        Ok(Json.obj("result"->"success"))
      }
    }
  }


}
